package com.ms.common.util;  

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.jfinal.kit.PropKit;

public class QRCodeUtil {  

	
	/**
	 * 生成二维码
	 * @param filePath
	 * @param content
	 * @return
	 * @throws WriterException
	 * @throws IOException
	 */
	
    public static String Encode(String content) throws WriterException, IOException {  
        String filePath=PropKit.get("QRPath");
		String osName=System.getProperties().getProperty("os.name");//windows 8
		if("Linux".equals(osName)){
			filePath=PropKit.get("QRPath_Linux");
		}else{
			filePath=PropKit.get("QRPath");
			
		}
        File tempFileDir=new File(filePath);  
        if(!tempFileDir.exists()){  
            tempFileDir.mkdirs();  
        }  
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");  
        String fileName = sdf.format(new Date())+".png";  
        
        int width = 250; // 图像宽度  
        int height = 250; // 图像高度  
        String format = "png";// 图像类型  
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,  
                BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵  
        Path path = FileSystems.getDefault().getPath(filePath, fileName);  
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像  
        return "/qrFile/"+fileName;
    }  

}  